// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './userAddStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from 'moment';
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { RangePicker } = DatePicker
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const userAddView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue ,validateFieldsAndScroll } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {selectData,tempArr, checkAll,parentIdList,query, actionType, btnLoading ,products,areaList,selectOptionData} = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };
  const formItemLayoutForTime = {
    labelCol: { span: 2 },
    wrapperCol: { span: 20 },
  };
  const checkboxStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
  };


  function goback(){
    hashHistory.push({
      pathname: '/home/expandManage/userList',
      query: {}
    });
  }
  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
  }
  function onCheckAllChange(e){
    checkAll = e.target.checked
    query.projectIdList = e.target.checked&&products.length?products.map((item)=>{
      return item.value
    }):[]
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {checkAll,query}
    })
    dispatch({
      type: `${namespace}/queryUserByPorject`,
      payload: {type:'全选'}
    })
  }

  function checkboxChange(checkedValues) {
    if(actionType == 'detail'){
      tempArr = []
      for(var item of query.orgList){
        for(var itemed of checkedValues){
          if(item.orgId == itemed){
            tempArr.push(item.zituoParentid)
          }
        }
      }
      query.parentId = tempArr.join(',')
    }

    query.projectIdList = checkedValues
    checkAll = checkedValues.length === products.length
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query,checkAll}
    })
    
  }
  function onCheckboxChange(e){
    if(e.target.checked){
      dispatch({
        type: `${namespace}/queryUserByPorject`,
        payload: {id:e.target.value}
      })
    }
  }

  function selectChange(value,it){
    tempArr = []
    if(actionType == 'detail'){
      let list = []
      for(var item of query.projectIdList){
        if(item !=it.value){
          list.push(item)
        }
      }
      list.push(it.value)
      query.projectIdList = list
      for(var item of query.orgList){
        if(item.orgId != it.value){
          tempArr.push(item.zituoParentid)
        }
      }
    }
    for(var item of products){
      if(item.value == it.value){
        item.userId = value
      }
    }
    parentIdList.push(value)

    tempArr.push(...parentIdList);
    // tempArr = [...new Set(tempArr)]
    if(actionType == 'detail'){
    query.parentId =  tempArr.join(',')
    }else{
    query.parentId = parentIdList.join(',')
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query,products}
    })
  }

  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {},
          callback:()=>{
            hashHistory.push({
              pathname: '/home/expandManage/userList',
              query: {areaId:query.areaId,projectId:query.projectId}
            })
          }
        })
      }
    })
  }

   //过滤项目数据
  function filterProjectList(areaId){
    products = []
    let list = []
    for(var item of areaList){
      for(var itemed of areaId){
        if(item.value == itemed){
          list.push(...item.children)
        }
      }
    }
    if(list.length){
      products =  list.map((item,index)=>{
        return {
          label: item.buname,
          value: item.buguid,
        }
      })
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {products}
    })
  }

  //区域改变时
  function inputAreaChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    filterProjectList(value)
  }

 

  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button type='primary' onClick={e => submit()} loading={btnLoading}>保存</Button>
        <Popconfirm placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => goback()} okText="确定" cancelText="取消">
          <Button>关闭</Button>
        </Popconfirm>
      </div>

      <CollapsiblePanels title="用户详情" hideUpDownBtn={true} >
      <Row>
          <Col span={8}>
            <FormItem label='姓名'  {...formItemLayoutPro}>
              {getFieldDecorator('name', {
                rules: [{
                  required: true, whitespace: true, message: '请输入姓名'
                }],
                initialValue: query.name
              })(
                <Input placeholder='请输入姓名' onChange={(e) => { inputChange(e.target.value, 'name') }} />
              )}
            </FormItem>
          </Col>
      </Row>
      <Row>
          <Col span={8}>
            <FormItem label='手机号码'  {...formItemLayoutPro}>
              {getFieldDecorator('phone', {
                rules: [{
                  required: true, whitespace: true, message: '请输入手机号码'
                }],
                initialValue: query.phone
              })(
                <Input type={'number'} placeholder='请输入手机号码' onChange={(e) => { inputChange(e.target.value, 'phone') }} />
              )}
            </FormItem>
          </Col>
      </Row>
      <Row>
          <Col span={8}>
            <FormItem label='渠道'  {...formItemLayoutPro}>
              {getFieldDecorator('userType', {
                rules: [{
                  required: true, whitespace: true, message: '请选择渠道'
                }],
                initialValue: query.userType
              })(
                <Select placeholder='请选择渠道' onChange={(e) => { inputChange(e, 'userType') }}>
                  <Select.Option value="2">行销自拓</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='人员类型'  {...formItemLayoutPro}>
              {getFieldDecorator('appRoleZituo', {
                rules: [{
                  required: true, whitespace: true, message: '请选择人员类型'
                }],
                initialValue: query.appRoleZituo
              })(
                <Select placeholder='请选择人员类型' disabled={query.appRoleZituo == '4'} onChange={(e) => { inputChange(e, 'appRoleZituo') }}>
                  <Select.Option value="1" style={{display:actionType == 'add'?'none':'block'}}>渠道经理</Select.Option>
                  <Select.Option value="2" style={{display:actionType == 'add'?'none':'block'}}>渠道主管</Select.Option>
                  <Select.Option value="3" style={{display:actionType == 'add'?'none':'block'}}>渠道专员</Select.Option>
                  <Select.Option value="4" style={{display:actionType == 'detail'?'none':'block'}}>小蜜蜂</Select.Option>
                  {/* <Select.Option value="5" style={{display:actionType == 'add'?'none':'block'}}>关键人</Select.Option> */}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{display: query.appRoleZituo == '4'?'block':'none'}}>
          <Col span={8}>
            <FormItem label='身份证号'  {...formItemLayoutPro}>
              {getFieldDecorator('idCode', {
                rules: [{
                  required: false, whitespace: true, message: '请输入身份证号'
                }],
                initialValue: query.idCode
              })(
                <Input placeholder='请输入身份证号' onChange={(e) => { inputChange(e.target.value, 'idCode') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{display: query.appRoleZituo == '4'?'block':'none'}}>
          <Col span={8}>
            <FormItem label='开户行'  {...formItemLayoutPro}>
              {getFieldDecorator('bankName', {
                rules: [{
                  required: false, whitespace: true, message: '请输入开户行'
                }],
                initialValue: query.bankName
              })(
                <Input placeholder='请输入开户行' onChange={(e) => { inputChange(e.target.value, 'bankName') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{display: query.appRoleZituo == '4'?'block':'none'}}>
          <Col span={8}>
            <FormItem label='银行卡号'  {...formItemLayoutPro}>
              {getFieldDecorator('bankCode', {
                rules: [{
                  required: false, whitespace: true, message: '请输入银行卡号'
                }],
                initialValue: query.bankCode
              })(
                <Input placeholder='请输入银行卡号' onChange={(e) => { inputChange(e.target.value, 'bankCode') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaId', {
                  initialValue: query.areaId || [],
                  rules: [
                    { required: true,  message: '请选择' },
                  ],
              })(
                <Select
                mode="multiple"
                size='default'
                placeholder="请选择区域"
                onChange={(e, v) => {
                  let arr = []
                  v.map((item, idx) => {
                    arr.push(item.props.value)
                  })
                  inputAreaChange(arr, 'areaId')
                }}
                style={{ width: '100%' }}
              >
                {areaList && areaList.map((item, idx) => {
                  return (
                    item?
                    <Select.Option key={idx+''} value={item.value}>{item.label}</Select.Option>:null
                  )
                })}
              </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row style={{marginBottom: '8px'}}>
          <Col span={16}>
                <Col span={3} style={{paddingRight: '.6%',textAlign:'right'}}><span style={{color: '#FF3B37'}}>*</span> 项目：</Col>
                <Col span={18}>
                  <Checkbox style={{marginBottom: '12px'}}
                      onChange={(e) =>{onCheckAllChange(e,'checkAll')}}
                      checked={checkAll}
                    >
                    全选
                  </Checkbox>
                  <Checkbox.Group style={{ width: '100%' }}  value={query.projectIdList} onChange={(e) =>{checkboxChange(e,'product')}}>
                  { products == undefined ?null:products.map((item,key)=>{
                  return <Row key={key}>
                          <Col span={24} className={cx('col_margin_bottom')}>
                              <div className={cx('flex')} style={{marginBottom: '12px'}}>
                              <Col span={10} className={cx('col_margin_bottom')}>
                                <Checkbox value={item.value} onChange={(e) =>{onCheckboxChange(e,'checkbox')}}>{item.label}</Checkbox>
                              </Col> 
                                <div className={cx('flex','flex_1')} style={{display:query.appRoleZituo=='4'||query.appRoleZituo=='5'?'block':'none'}}>
                                  <span>归属人：</span>
                                    <Select disabled={actionType == 'check'}   size='small' style={{ width: 210 }} value={item.userId}  onChange={(e)=>{selectChange(e,item)}}>
                                        { item.selectOptionData == undefined ?null:item.selectOptionData.map((itemed,key1)=>{
                                          return <Select.Option value={itemed.value} key={key1}>{itemed.label}</Select.Option>
                                        })}
                                    </Select>
                                </div>
                              </div> 
                            </Col>
                          </Row>
                    })}
                  </Checkbox.Group>
                </Col>
          </Col>
        </Row>
       
      </CollapsiblePanels>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(userAddView))